<?php

namespace App\Models\Workflow;

use App\Enums\Workflow\WorkflowEnum;
use App\Models\BaseModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use App\Service\OpenShop\User\RmsUserService;
use Illuminate\Database\Eloquent\Relations\HasOne;

class WorkflowV2OrderLogModel extends BaseModel
{
    use KfUid;
    use KfSoftDeletes;

    protected $table = 'workflow_v2_order_logs';

    protected $fillable = [
        'workflowOrderId',
        'workflowOrderNodeId',
        'nodeName',
        'handlerUid',
        'handlerName',
        'audit',
        'content',
        'rejectNodeId',
        'status',
        'isDeleted'
    ];

    const STATUS_WAIT   = 0;
    const STATUS_FINISH = 1;
    const STATUS_REJECT = 2;
    const STATUS_TEXT   = [
        self::STATUS_WAIT   => '待完成',
        self::STATUS_FINISH => '已完成',
        self::STATUS_REJECT => '已驳回',
    ];

    const AUDIT_DEFAULT = 0;
    const AUDIT_YES     = 1;
    const AUDIT_NO      = 2;
    const AUDIT_TEXT    = [
        self::AUDIT_DEFAULT => '',
        self::AUDIT_YES     => '通过',
        self::AUDIT_NO      => '驳回',
    ];

    public function workflowOrderNodeRel(): HasOne
    {
        return $this->hasOne(WorkflowV2OrderNodeModel::class, 'id', 'workflowOrderNodeId');
    }

    /**
     * 创建待处理节点日志
     * @param int $workflowOrderId
     * @param int $workflowOrderNodeId
     */
    public function add(int $workflowOrderId, int $workflowOrderNodeId, int $userId, int $status = self::STATUS_WAIT)
    {
        $nodeModel = WorkflowV2OrderNodeModel::query()->where('id', $workflowOrderNodeId)->first();
        if (!$nodeModel) {
            return null;
        }

        if ($userId) {
            $handlerName = RmsUserService::getRmsUserInfoByUserIds([$userId], [], true)['data'][0]['username'] ?? '';
        } else {
            $handlerName = '';
        }

        return self::query()
                   ->create([
                       'workflowOrderId'     => $workflowOrderId,
                       'workflowOrderNodeId' => $workflowOrderNodeId,
                       'nodeName'            => $nodeModel->name,
                       'handlerUid'          => $userId,
                       'handlerName'         => $handlerName,
                       'audit'               => self::AUDIT_DEFAULT,
                       'rejectNodeId'        => 0,
                       'status'              => $status,
                   ]);
    }

    /**
     * 节点完成
     * @param int $workflowOrderId
     * @param int $workflowOrderNodeId
     * @param int $userId
     * @param int $audit
     * @param string $content
     * @param array $imgFiles
     * @return int
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function finish(
        int $workflowOrderId,
        int $workflowOrderNodeId,
        int $userId,
        int $audit,
        string $content,
        array $imgFiles
    ) {
        $conditions = [
            'workflowOrderId'     => $workflowOrderId,
            'workflowOrderNodeId' => $workflowOrderNodeId,
            'status'              => self::STATUS_WAIT
        ];
        if (!self::query()->where($content)->exists()) {
            $this->add($workflowOrderId, $workflowOrderNodeId, $userId);
        }
        return self::query()
                   ->where($conditions)
                   ->update([
                       'handlerUid'  => $userId,
                       'handlerName' => RmsUserService::getRmsUserInfoByUserIds([$userId], [],
                               true)['data'][0]['username'] ?? '',
                       'audit'       => $audit,
                       'content'     => $content,
                       'imgFiles'    => $imgFiles,
                       'status'      => $audit == self::AUDIT_YES ? self::STATUS_FINISH : self::STATUS_REJECT,
                   ]);
    }

    /**
     * 完成节点并生成下一个待处理节点
     * @param int $workflowOrderId
     * @param int $workflowOrderNodeId
     * @return void
     */
//    public function finish(
//        int $workflowOrderId,
//        int $currentNodeId,
//        int $dealUid,
//        int $nextNodeId,
//        int $audit,
//        string $content,
//        int $rejectNodeId
//    ): void {
//
//        if ($audit == self::AUDIT_NO) {
//            $status = self::STATUS_REJECT;
//        } else {
//            $status = self::STATUS_FINISH;
//        }
//
//        $currentLog = self::query()
//            ->where('workflowOrderId', $workflowOrderId)
//            ->where('workflowOrderNodeId', $currentNodeId)
//            ->orderByDesc('id')
//            ->first();
//
//        // 更新特殊日志的处理人
//        if ($dealUid && $currentLog->handlerUid != $dealUid) {
//            $currentLog->handlerUid  = $dealUid;
//            $currentLog->handlerName = RmsUserService::getRmsUserInfoByUserIds([$dealUid], [],
//                true)['data'][0]['username'] ?? '';
//        }
//
//        $currentLog->status       = $status;
//        $currentLog->audit        = $audit;
//        $currentLog->content      = $content;
//        $currentLog->rejectNodeId = $rejectNodeId;
//        $currentLog->save();
//
//        if ($audit == self::AUDIT_NO) {
//
//            // 驳回 - 跳转到指定节点
//            $this->add($workflowOrderId, $rejectNodeId);
//            return;
//        }
//
//        // 获取下个节点
//        if ($nextNodeId <= 0) {
//            return;
//        }
//
//        $nextNode = WorkflowOrderNodeModel::query()->where('id', $nextNodeId)->first();
//
//        // 简单节点
//        if ($nextNode->nodeType == WorkflowEnum::NODE_TYPE_SEQUENCE) {
//            $this->add($workflowOrderId, $nextNodeId);
//            return;
//        }
//
//        // 复杂节点
//        WorkflowOrderNodeModel::query()
//                              ->where('pId', $nextNodeId)
//                              ->get()
//                              ->each(function ($item) use ($workflowOrderId) {
//                                  $this->add($workflowOrderId, $item->id);
//                              });
//    }


    /**
     * 内部人看到的审批日志
     * @param int $workflowOrderId
     */
    public function kfLogs(int $workflowOrderId)
    {
        return self::query()
                   ->where('workflowOrderId', $workflowOrderId)
                   ->get()
                   ->map(function (self $item) {
                       return [
                           'nodeName'    => $item->nodeName,
                           'handlerName' => $item->handlerName,
                           'status'      => $item->status,
                           'statusText'  => self::STATUS_TEXT[$item->status] ?? '-',
                           'createdAt'   => $item->createdAt->toDateTimeString(),
                           'content'     => $item->content,
                       ];
                   });
    }
}
